package me.zingon.open.bigsmart.worker.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;
import me.zingon.open.bigsmart.model.Job;
import me.zingon.open.bigsmart.model.topic.HttpBody;
import me.zingon.open.bigsmart.queue.JobPoll;
import me.zingon.open.bigsmart.worker.IWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author ztc 1423047407@qq.com
 * @version 1.0
 * @date 2020-8-6 15:30
 */
@Component
@Slf4j
public class HttpTopicWorker implements IWorker {

    @Autowired
    JobPoll jobPoll;

    @Override
    public void work(Job job) {
        log.info("HttpTopicTimer消费：{}", job);
        HttpBody httpBody = new HttpBody(job.getBody());
        try {
            String result = null;
            if (httpBody.getMethod().toLowerCase().equals("get")) {
                result = this.get(httpBody);
            } else {
                result = this.post(httpBody);
            }
            log.info("返回：{}", result);
            if (result.contains(httpBody.getPassrule())) {
                jobPoll.rm(job.getTopic(), job.getId());
                log.info("http消费成功");
                return;
            }
            throw new Exception("http消费失败");
        } catch (Exception e) {
            log.info("http消费失败：{}", e.getMessage());
            if (System.currentTimeMillis() - job.getCreateTime() > 60 * 1000) {
                jobPoll.rm(job.getTopic(), job.getId());
            }
        }
    }
 

    private String post(HttpBody httpBody) {
        String result = HttpRequest.post(httpBody.getUrl())
                .addHeaders(httpBody.getHeaders())
                .body(httpBody.getBody())
                .execute()
                .body();
        return result;
    }


    private String get(HttpBody httpBody) {
        return HttpRequest.get(httpBody.getUrl())
                .addHeaders(httpBody.getHeaders())
                .form(new JSONObject(httpBody.getBody()))
                .execute()
                .body();
    }
}
